package com.xipu.yygh.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xipu.yygh.common.exception.YyghException;
import com.xipu.yygh.common.result.ResultCodeEnum;
import com.xipu.yygh.enums.OrderStatusEnum;
import com.xipu.yygh.feign.service_hosp.HospFeignClient;
import com.xipu.yygh.feign.service_user.UserFeignClient;
import com.xipu.yygh.model.order.OrderInfo;
import com.xipu.yygh.model.user.Patient;
import com.xipu.yygh.order.mapper.OrderInfoMapper;
import com.xipu.yygh.order.service.OrderInfoService;
import com.xipu.yygh.order.service.WeixinService;
import com.xipu.yygh.order.utils.HttpRequestHelper;
import com.xipu.yygh.rabbit.constant.MqConst;
import com.xipu.yygh.rabbit.service.RabbitService;
import com.xipu.yygh.vo.hosp.ScheduleOrderVo;
import com.xipu.yygh.vo.msm.MsmVo;
import com.xipu.yygh.vo.order.OrderCountQueryVo;
import com.xipu.yygh.vo.order.OrderCountVo;
import com.xipu.yygh.vo.order.OrderMqVo;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author gql
 * @since 2022-05-12
 */
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {

    /**
     * 用户模块feign
     */
    @Autowired
    private UserFeignClient userFeignClient;

    /**
     * 医院模块feign
     */
    @Autowired
    private HospFeignClient hospFeignClient;

    /**
     * RabbitMQ发送消息
     */
    @Autowired
    private RabbitService rabbitService;


    /**
     * 微信支付
     */
    @Autowired
    private WeixinService weixinService;

    @Override
    public Long saveOrder(String scheduleId, Long patientId) {
        // 1.feign获取就诊人信息
        Patient patient = this.userFeignClient.getPatientOrder(patientId);

        // 2.feign获取排班信息
        ScheduleOrderVo scheduleOrderVo = this.hospFeignClient.getScheduleOrderVo(scheduleId);

        // 3.httpclient调用医院系统接口,确认号是否存在
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("hoscode", scheduleOrderVo.getHoscode());
        paramMap.put("depcode", scheduleOrderVo.getDepcode());
        paramMap.put("hosScheduleId", scheduleOrderVo.getHosScheduleId());
        paramMap.put("reserveDate", new DateTime(scheduleOrderVo.getReserveDate()).toString("yyyy-MM-dd"));
        paramMap.put("reserveTime", scheduleOrderVo.getReserveTime());
        paramMap.put("amount", scheduleOrderVo.getAmount());
        paramMap.put("name", patient.getName());
        paramMap.put("certificatesType", patient.getCertificatesType());
        paramMap.put("certificatesNo", patient.getCertificatesNo());
        paramMap.put("sex", patient.getSex());
        paramMap.put("birthdate", patient.getBirthdate());
        paramMap.put("phone", patient.getPhone());
        paramMap.put("isMarry", patient.getIsMarry());
        paramMap.put("provinceCode", patient.getProvinceCode());
        paramMap.put("cityCode", patient.getCityCode());
        paramMap.put("districtCode", patient.getDistrictCode());
        paramMap.put("address", patient.getAddress());
        paramMap.put("contactsName", patient.getContactsName());
        paramMap.put("contactsCertificatesType", patient.getContactsCertificatesType());
        paramMap.put("contactsCertificatesNo", patient.getContactsCertificatesNo());
        paramMap.put("contactsPhone", patient.getContactsPhone());
        paramMap.put("timestamp", HttpRequestHelper.getTimestamp());
        // 这里关闭了signKey校验
        //String md5pwd = DigestUtils.md5DigestAsHex(password.getBytes());
        paramMap.put("sign", "");

        JSONObject result = HttpRequestHelper.sendRequest(paramMap, "http://localhost:8203/order/submitOrder");
        if (result.getInteger("code") == 200) {
            JSONObject jsonObject = result.getJSONObject("data");
            String hosRecordId = jsonObject.getString("hosRecordId");
            Integer number = jsonObject.getInteger("number");
            String fetchTime = jsonObject.getString("fetchTime");
            String fetchAddress = jsonObject.getString("fetchAddress");

            // 4.填充订单信息表(使用就诊人信息、排班数据信息、号源信息)
            OrderInfo orderInfo = new OrderInfo();
            // 4.1 设置排班信息
            BeanUtils.copyProperties(scheduleOrderVo, orderInfo);
            // 4.2 医院系统返回的号源信息
            orderInfo.setHosRecordId(hosRecordId);
            orderInfo.setNumber(number);
            orderInfo.setFetchTime(fetchTime);
            orderInfo.setFetchAddress(fetchAddress);
            // 4.3 设置就诊人信息：流水号(时间戳+随机数)、排班id、订单状态
            String outTradeNo = System.currentTimeMillis() + "" + new Random().nextInt(100);
            orderInfo.setOutTradeNo(outTradeNo);
            orderInfo.setScheduleId(scheduleId);
            orderInfo.setOrderStatus(OrderStatusEnum.UNPAID.getStatus());
            orderInfo.setUserId(patient.getUserId());
            orderInfo.setPatientId(patientId);
            orderInfo.setPatientName(patient.getName());
            orderInfo.setPatientPhone(patient.getPhone());

            this.baseMapper.insert(orderInfo);

            // 根据医院返回数据，更新排班数量
            Integer reservedNumber = jsonObject.getInteger("reservedNumber");
            Integer availableNumber = jsonObject.getInteger("availableNumber");

            // 5. 封装订单信息发送消息给医院
            // 设置更新号源和短信通知
            OrderMqVo orderMqVo = new OrderMqVo();
            orderMqVo.setScheduleId(scheduleId);
            orderMqVo.setReservedNumber(reservedNumber);
            orderMqVo.setAvailableNumber(availableNumber);
            // 设置就诊人手机号手机号
            MsmVo msmVo = new MsmVo();
            msmVo.setPhone(patient.getPhone());
            orderMqVo.setMsmVo(msmVo);
            //String reserveDate =
            //        new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd")
            //                + (orderInfo.getReserveTime()==0 ? "上午": "下午");
            //Map<String,Object> param = new HashMap<String,Object>(){{
            //    put("title", orderInfo.getHosname()+"|"+orderInfo.getDepname()+"|"+orderInfo.getTitle());
            //    put("amount", orderInfo.getAmount());
            //    put("reserveDate", reserveDate);
            //    put("name", orderInfo.getPatientName());
            //    put("quitTime", new DateTime(orderInfo.getQuitTime()).toString("yyyy-MM-dd HH:mm"));
            //}};
            //msmVo.setParam(param);

            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_ORDER, MqConst.ROUTING_ORDER, orderMqVo);

            // 6.返回订单Id
            return orderInfo.getId();
        } else {
            throw new YyghException(20001, "挂号失败");
        }
    }

    @Override
    public OrderInfo getOrderInfo(Long orderId) {
        OrderInfo orderInfo = this.baseMapper.selectById(orderId);
        orderInfo.getParam().put("orderStatus", OrderStatusEnum.getStatusNameByStatus(orderInfo.getOrderStatus()));
        return orderInfo;
    }

    @Override
    public Boolean cancelOrder(Long orderId) {
        // 1.查询订单信息
        OrderInfo orderInfo = this.baseMapper.selectById(orderId);
        if (ObjectUtils.isEmpty(orderInfo)) {
            throw new YyghException(20001, "订单信息不存在");
        }
        orderInfo.getParam().put("orderStatus", OrderStatusEnum.getStatusNameByStatus(orderInfo.getOrderStatus()));

        // 2.使用map集合封装医院系统需要的数据
        Map<String, Object> reqMap = new HashMap<>();
        reqMap.put("hoscode", orderInfo.getHoscode());
        reqMap.put("hosRecordId", orderInfo.getHosRecordId());
        reqMap.put("timestamp", HttpRequestHelper.getTimestamp());
        String sign = DigestUtils.md5DigestAsHex("1".getBytes());
        reqMap.put("sign", sign);

        // 3.调用医院系统接口,查看号码是否可以取消,如果现在已经过了最晚退号时间,就不允许取消预约
        DateTime quitTime = new DateTime(orderInfo.getQuitTime());
        if (quitTime.isBeforeNow()) {
            throw new YyghException(20001, "已超时,不能取消预约");
        }
        // 更新取消预约的状态
        JSONObject result = HttpRequestHelper.sendRequest(reqMap, "http://localhost:8203/order/updateCancelStatus");

        // TODO: bug,退款时,签名校验有问题,暂时搁置,不进行判断
        // 4.根据医院返回数据判断,如果返回成功,可以取消
        if (result.getInteger("code") != 200) {
            throw new YyghException(ResultCodeEnum.FAIL.getCode(), result.getString("message"));
        }

        // 5.若订单是已支付状态,执行微信退款操作
        if (orderInfo.getOrderStatus().intValue() == OrderStatusEnum.PAID.getStatus().intValue()) {
            boolean isRefund = weixinService.refund(orderId);
            // 订单若未支付,则不退款
            if (!isRefund) {
                throw new YyghException(20001, "退款失败");
            }
        }

        // 6.更新订单状态
        orderInfo.setOrderStatus(OrderStatusEnum.CANCLE.getStatus());
        this.baseMapper.updateById(orderInfo);

        // 7.使用mq发送消息给hosp模块,更新排班(号)数量
        //发送mq信息更新预约数 我们与下单成功更新预约数使用相同的mq信息，不设置可预约数与剩余预约数，接收端可预约数加1即可
        OrderMqVo orderMqVo = new OrderMqVo();
        orderMqVo.setScheduleId(orderInfo.getScheduleId());
        //短信提示
        MsmVo msmVo = new MsmVo();
        msmVo.setPhone(orderInfo.getPatientPhone());
        orderMqVo.setMsmVo(msmVo);
        this.rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_ORDER, MqConst.ROUTING_ORDER, orderMqVo);
        return true;
    }

    @Override
    public void patientTips() {
        // 1.查询订单信息列表
        List<OrderInfo> orderInfoList = this.baseMapper.selectList(Wrappers.lambdaQuery(OrderInfo.class)
                // 就诊日期为今天
                .eq(OrderInfo::getReserveDate, LocalDate.now())
                // 查询订单状态不为-1的数据
                .ne(OrderInfo::getOrderStatus, OrderStatusEnum.CANCLE.getStatus()));
        // 2. 封装短信Vo,使用RabbitMQ发送消息
        for (OrderInfo orderInfo : orderInfoList) {
            MsmVo msmVo = new MsmVo();
            // 得到每个挂号人的手机号
            msmVo.setPhone(orderInfo.getPatientPhone());
            // 得到其他挂号信息
            String reserveDate = LocalDate.now() + (orderInfo.getReserveTime() == 0 ? "上午" : "下午");
            Map<String, Object> param = new HashMap<String, Object>() {{
                put("title", orderInfo.getHosname() + "|" + orderInfo.getDepname() + "|" + orderInfo.getTitle());
                put("reserveDate", reserveDate);
                put("name", orderInfo.getPatientName());
            }};
            msmVo.setParam(param);
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_MSM, MqConst.ROUTING_MSM_ITEM, msmVo);
        }
    }

    @Override
    public Map<String, Object> getCountMap(OrderCountQueryVo orderCountQueryVo) {
        // 1.查询每天预约数量
        List<OrderCountVo> orderCountVoList = this.baseMapper.selectOrderCount(orderCountQueryVo);
        // 获取统计日期列表
        List<String> dateList = orderCountVoList.stream().map(OrderCountVo::getReserveDate).collect(Collectors.toList());
        // 获取统计数量列表
        List<Integer> countList = orderCountVoList.stream().map(OrderCountVo::getCount).collect(Collectors.toList());
        Map<String, Object> map = new HashMap<>();
        // x轴 日期
        map.put("dateList", dateList);
        // y轴 数量
        map.put("countList", countList);
        return map;
    }
}
